#include "Animation.h"
#include "GraphCache.h"
#include "T_Scene.h"

Animation::Animation(){
	index=0;
	m_Interval=0;
	m_Duration=0;
	m_BMPs=NULL;
	m_Sequence=NULL;
}

Animation::~Animation(){
	if(m_BMPs!=NULL){
		delete[] m_BMPs;
		m_BMPs=NULL;
	}
}

Animation *Animation::create(const std::string &seq,float interval){
	Animation *ret=new Animation();
	if(ret->setSequence(seq)){
		ret->setInterval(interval);
		return ret;
	}
	delete ret;
	return NULL;
}

bool Animation::init(T_Node *node){
	T_Sprite *sprite=dynamic_cast<T_Sprite *>(node);
	if(NULL==sprite || NULL==m_Sequence || NULL==m_BMPs){
		return false;
	}
	setTarget(node);
	index=m_Sequence->from;
	sprite->setTexture(m_BMPs[index],true);
	return true;
}

void Animation::startWithTarget(T_Node *node){
	if(!init(node))return;
	T_Scene *scene_Current=node->getScene();
	if(NULL==scene_Current){
		return;
	}
	ActionPool &pool=scene_Current->getActionPool();
	pool.removeAll(node,this->getActionType());
	pool.add(this);
}

bool Animation::isDone()const{
	return false;
}

void Animation::update(int dt){
	if(m_Target==NULL || m_Sequence==NULL || m_BMPs==NULL){
		return;
	}

	m_Duration+=dt;
	if(m_Duration>=m_Interval){
		m_Duration=0;
		index++;
		if(index>m_Sequence->to){
			index=m_Sequence->from;
		}
		T_Sprite *sprite=dynamic_cast<T_Sprite *>(m_Target);
		sprite->setTexture(m_BMPs[m_Sequence->array[index]],false);
	}
}

bool Animation::setSequence(const std::string& nameSequence){
	m_Sequence=SequenceManager::getInstance().find(nameSequence);
	if(NULL==m_Sequence){
		return false;
	}
	index=m_Sequence->from;
	T_BITMAP *bitmap=GraphCache::getInstance()->get(m_Sequence->graph);
	if(bitmap==NULL){
		return false;
	}
	if(m_BMPs!=NULL){
		delete[]m_BMPs;
	}
	int count=bitmap->getCols()*bitmap->getRows();
	m_BMPs=new HBITMAP[count];
	if(1==count){
		m_BMPs[0]=bitmap->getBMP();
	}else{
		for(int i=0;i<count;i++){
			m_BMPs[i]=bitmap->getRegion(i);
		}
	}
	return true;
}